package com.threedt.nova.portfolio.reader;


import java.io.IOException;
import java.io.Serializable;
import java.net.URL;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.integration.core.Message;
import org.springframework.integration.message.MessageBuilder;
import org.springframework.integration.message.MessageSource;

import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.fetcher.FeedFetcher;
import com.sun.syndication.fetcher.FetcherException;
import com.sun.syndication.fetcher.FetcherListener;
import com.sun.syndication.fetcher.impl.FeedFetcherCache;
import com.sun.syndication.fetcher.impl.HashMapFeedInfoCache;
import com.sun.syndication.fetcher.impl.HttpURLFeedFetcher;
import com.sun.syndication.io.FeedException;


public class RssReader implements MessageSource, InitializingBean , Serializable {
   
	
	    private FeedFetcherCache feedInfoCache;
	    private FeedFetcher feedFetcher;
	    private FetcherListener fetcherListener;

	    public Message<SyndFeed> receive() {
	        System.out.println("readRssFeed method is called");
	        SyndFeed feed = obtainFeedItems();
	        return MessageBuilder.withPayload(feed)
	                .setHeader("feedid", "gridshore").build();

	    }

	    private SyndFeed obtainFeedItems() {
	        SyndFeed feed = null;
	        try {
	            feed = feedFetcher.retrieveFeed(new URL("http://www.gridshore.nl/feed/"));
	        } catch (IOException e) {
	        	System.out.println("IO Problem while retrieving feed"+ e);
	        } catch (FeedException e) {
	        	System.out.println("Feed Problem while retrieving feed"+ e);
	        } catch (FetcherException e) {
	        	System.out.println("Fetcher Problem while retrieving feed"+ e);
	        }
	        return feed;
	    }

	    public void afterPropertiesSet() throws Exception {
	        feedInfoCache = HashMapFeedInfoCache.getInstance();
	        feedFetcher = new HttpURLFeedFetcher(feedInfoCache);
	        if (fetcherListener != null) {
	            feedFetcher.addFetcherEventListener(fetcherListener);
	        }
	    }

	    public void setFetcherListener(FetcherListener fetcherListener) {
	        this.fetcherListener = fetcherListener;
	    }

}

